/* gm_medula.c -- Objeto superior de controle
 *
 * Copyright (C) 2008, Diogo F. S. Ramos <diogo.ramos@usp.br>
 * GEAR - Grupo de Estudos Avançados em Robótica
 * <http://www.sel.eesc.usp.br/gear>
 *
 * This file is part os GEARMedula.
 * 
 * GEARMedula is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, version 3 of the
 * License.
 * 
 * GEARMedula is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

#include "gm_utils.h"
#include "gm_medula.h"

/* Static */
static void gm_medula_wait( gm_medula_t * self );

gm_medula_t *
gm_medula_new( void )
{
    gm_medula_t * self = NULL;

    self = XMALLOC( gm_medula_t, 1 );

    /* Iniciando ponteiros */
    self->server = NULL;
    self->monitor = NULL;
    self->control = NULL;

    /* Iniciando variáveis */
    self->sim_enabled = 0;

    return self;
}

void
gm_medula_destroy( gm_medula_t * self )
{
    gm_server_destroy( self->server );
    gm_monitor_destroy( self->monitor );
    gm_control_destroy( self->control );

    XFREE( self );
}

/** Inicia a execução do objeto Medula.
 *
 * Cria e executa os objetos e módulos.
 *
 * @param *self Objeto gm_medula_t.
 *
 * @param *args_passed Ponteiro para o objeto que contem as
 * informações dos argumentos passados pelo terminal.
 *
 */
void
gm_medula_init( gm_medula_t * self, gm_args_t * args_passed )
{
    /* Criando um servidor */
    self->server = gm_server_new( args_passed->server_port );

    /* Criando (ou não) o simulador */
    if( !args_passed->server_real )
    {
	gm_sim_run();
	self->sim_enabled = 1;
    }

    /* Criando um monitor */
    self->monitor = gm_monitor_new( args_passed->server_real );
    /* Adicionando o monitor ao servidor */
    gm_server_add_monitor( self->server,
			   self->monitor );
    /* Ligando ou não o display do monitor */
    gm_monitor_display_enable( self->monitor,
			       args_passed->f_server_display );
    
    
    /* Criando um controle */
    self->control = gm_control_new( args_passed->server_real,
				    args_passed->serial_path);
    /* Adicionando o control ao servidor */
    gm_server_add_control( self->server,
			   self->control );

    /* Iniciando servidor */
    gm_server_init( self->server );

    gm_medula_wait( self );
}

static void
gm_medula_wait( gm_medula_t * self )
{
    char opcao[2] = { "c" };
    
    while( opcao[0] != 'q' )
	fgets(opcao, 2, stdin);

    gm_medula_destroy( self );
}
